#include "ABM_Properties.h"

//recorro la lista y libero los paquetes de la lista
ABM_Properties::~ABM_Properties()
{
    std::list<Paquete*>::iterator it = this->ListadoKV.begin();
    while ( it != this->ListadoKV.end() )
    {
        delete *it;
        it++;
    }
    //luego, la lista de punteros se elimina naturalmente
    //al unwindearse el stack
}

    //devuelve null si no encuentra nada
std::list<Paquete*>::iterator ABM_Properties::FindIt(const std::string& Key,bool& F)
{
    bool found = false;
    std::list<Paquete*>::iterator it = this->ListadoKV.begin();
    while ( it != this->ListadoKV.end() )
    {
        Paquete* P = *it;
        if ( P->Key == Key )
        {
            found = true;
            break;
        }
        it++;
    }
    F = found;
    return it;
}

std::string ABM_Properties::GetValueFromKey(const std::string& Key)
{
    std::string RetVal = "" ;
    bool found;
    std::list<Paquete*>::iterator it = this->FindIt(Key,found);
    if ( found ){RetVal = (*it)->Value ;}
    return RetVal;
}

bool ABM_Properties::Escribir(const std::string& K, const std::string& V)
{
    bool found;
    std::list<Paquete*>::iterator it = this->FindIt(K,found);
    if ( found )
    {
        (*it)->Value = V;
    }
    else
    {
        Paquete* P = new Paquete(K,V);
        this->ListadoKV.push_back( P );
    }
    return found;
}

bool ABM_Properties::Eliminar(const std::string& K)
{
    bool found = false;
    std::list<Paquete*>::iterator it = this->FindIt(K,found);
    if ( found )
    {
        this->ListadoKV.erase(it);
    }
    return found;
}

void ABM_Properties::LevantarFile()
{
    std::ifstream Properties;
    Properties.open( this->RutaArchivo.c_str() );
    if ( Properties.is_open() )
    {
        if ( !(Properties.peek() == std::ifstream::traits_type::eof()) )
        {
            std::string aux;
            while( getline(Properties,aux) )
            {
                int pos = aux.find("=");
                std::string K;
                std::string V;
                K = aux.substr(0,pos);
                V = aux.substr( pos+1 , aux.size()-pos-1 );
                Paquete* P = new Paquete(K,V);
                this->ListadoKV.push_back(P);
            }
        }
    }
    Properties.close();
}

void ABM_Properties::VolcarFile()
{
    std::ofstream Properties;
    Properties.open( this->RutaArchivo.c_str() ,std::ofstream::trunc );
    if ( Properties.is_open() )
    {
        std::list<Paquete*>::iterator it = this->ListadoKV.begin();
        while ( it != this->ListadoKV.end() )
        {
            std::string Linea;
            Paquete* P = *it;
            Linea = P->Key + "=" + P->Value;
            Properties << Linea << std::endl;
            it++;
        }
    } else { throw MyException("No se pudo abrir el archivo");}
    Properties.close();
}
